<!-- 角色信息 -->
<template>
  <div class="table">
    <el-tabs v-model="activeName" @tab-click="handleChangeTabs">
      <el-tab-pane label="角色信息" name="one">
        <div class="container">
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>
                <el-icon>
                  <Search />
                </el-icon> 查询条件：
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-row :gutter="10">
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-input v-model.trim="searchCondition.name" placeholder="角色名称"></el-input>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
              <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>
                查询结果：</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="handle-box">
            <el-button type="primary" :icon="Plus" class="mr10" :disabled="disabledbtn" @click="setActiveName('two')">新增
            </el-button>
            <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete('deleteRole')">
              <template #reference>
                <el-button type="danger" :icon="Delete" class="mr10" :disabled="disabledbtn">批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
          <el-table :data="tableState.tableList.slice((pageNumber - 1) * pageSize, pageNumber * pageSize)" border
            class="table" ref="multipleTableRef" v-loading="tableLoading" :reserve-selection="true"
            @row-dblclick="rowDblclick">
            <el-table-column type="index" align="center"> </el-table-column>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <!-- <el-table-column prop="code"
                             label="角色编码"
                             align="center">
            </el-table-column> -->
            <el-table-column prop="name" label="角色名称" align="center">
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" align="center" :formatter="handleFormatterCreateTime">
            </el-table-column>
            <!-- <el-table-column prop="description"
                             label="描述"
                             align="center">
            </el-table-column> -->
            <!-- <el-table-column label="是否可用"
                             width="120"
                             align="center">
              <template slot-scope="scope">
                <el-switch :value="(scope.row.enabled === 0 ? true : false)"
                           active-color="#13ce66"
                           inactive-color="#dcdfe6"
                           @change="handleEnale(scope.row)">
                </el-switch>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" text :icon="Menu" @click="handleAssignMenu(scope.row)">
                  分配菜单
                </el-button>
                <div class="mlr10 display-inline-block">
                  <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo('deleteRole', [id])">
                    <template #reference>
                      <el-button text :icon="Delete" size="small" class="red" @click="id = scope.row.id">删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background @update:current-page="handleCurrentChange" @update:page-size="handleSizeChange"
              layout="total, sizes, prev, pager, next, jumper" :page-size="pageSize" :current-page="pageNumber"
              :page-sizes="pageSizes" :total="total" :hide-on-single-page="false">
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="分配菜单" name="two">
        <el-card class="box-card">
          <div class="wzg-center width400">
            <el-form ref="roleFormRef" :model="roleForm" :rules="rules" v-loading="formLoading" label-width="100px">
              <el-row :gutter="10">
                <el-col :span="20">
                  <el-form-item label="角色名称：" prop="name">
                    <el-input v-model.trim="roleForm.name" placeholder="角色名称">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="20">
                  <el-form-item label="权限管理：" prop="selectAll">
                    <el-checkbox v-model.trim="roleForm.selectAll">全选/不全选</el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-card shadow="never">
              <el-tree :data="state.menuData" show-checkbox node-key="id" ref="treeRef" default-expand-all
                :props="defaultProps" :default-checked-keys="state.checkedKeys" @check="handleCheckMenu">
              </el-tree>
            </el-card>
            <div class="footer-center">
              <el-button @click="cancelSubmit">返 回</el-button>
              <el-button type="warning" plain :disabled="disabledbtn" @click="roleForm.selectAll = false">清空</el-button>
              <el-button type="primary" :disabled="disabledbtn"
                @click="submitForm('commonRoleInfo', getTableInfo, handleValidAssignment)">确 定</el-button>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup>
import { reactive, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { View, Delete, Edit, Search, Plus, Refresh, Menu } from '@element-plus/icons-vue';
import { common as Common } from '@/utils/common.js';
import { api as Request, imageUrl, uploadUrl } from '@/utils/api';
import { useTable } from '@/hooks/useTable.js';
import { useTabsForm } from '@/hooks/useTabsForm.js';
import useRules from '@/hooks/useRules.js';

const disabledbtn = ref(false);/*  按钮可用与不可用 */
const formLoading = ref(false);/*  对话框中数据提交加载 */
let { total, pageNumber, pageSize, pageSizes, multipleTableRef, tableLoading, tableState, searchCondition,
  handleCurrentChange, handleSizeChange, getTableInfo, searchInfo, resetSearch, batchDelete, deleteInfo, rowDblclick } =
  useTable({
    type_name: ''
  }, 'getRoleInfo', disabledbtn, 'FRONT_END');

let { formRef: roleFormRef, formData: roleForm, methodType, isDisabledbtn,
  activeName, setActiveName, handleChangeTabs, submitForm, handleClearData: cancelSubmit } = useTabsForm({
    id: '',
    // code: '',
    name: '',
    auth_ids: '104',
    selectAll: false
    // description: ''
  }, disabledbtn, handleCustomOperation, formLoading);
const state = reactive({
  menuData: [],/* 所有资源信息 */
  checkedKeys: [104],
  allKeys: [],
  resourceAllData: [], /* 所有分组的全部资源 */
  checkAllList: [], /* 全选的值true or false */
  checkedResourceList: [], /* 分组的资源 */
  checkedResource: [], /* 全部的资源 */
  isIndeterminateList: []
});
const defaultProps = reactive({
  children: 'items',
  label: 'title'
})
/* 校验规则 */
const rules = useRules('roleInfoRules');/* 校验规则 */
const id = ref(-1); /* 删除时所需的编号 删除时的id */
const treeRef = ref(''); /* 树的节点 */


/* 格式化创建时间 */
const handleFormatterCreateTime = (row, column) => {
  const time = row.create_time;
  if (['', null, 0].includes(time)) return '--';
  return Common.dateFormatYMDHMS(time * 1000);
}
/* 多选框全选事件 */
const handleCheckAllChange = (index, val) => {
  state.checkedResourceList[index] = val
    ? state.resourceAllData[index].id
    : [];
  state.checkAllList[index] = val;
  state.isIndeterminateList[index] = false;
}

/* 获取所有菜单信息 */
const getMyRoleInfo = (params) => {
  Request.getMyRoleInfo({})
    .then((res) => {
      if (res.status === 1 && res.result.length !== 0) {
        state.menuData = res.result;
        handleGetMenuIds(res.result);
        /* 系统首页 默认选中，并禁用 */
        for (let i = 0; i < state.menuData.length; i++) {
          /* 104不改 */
          if (state.menuData[i].id === 104) {
            state.menuData[i].disabled = true;
            break;
          }
        }
      }
    })
    .catch((res) => { }).finally(() => { disabledbtn.value = false; });
}
/* 点击tree事件 */
const handleCheckMenu = (checkedNodes, checkedKeys) => {
  const auth_ids = [
    ...checkedKeys.halfCheckedKeys,
    ...checkedKeys.checkedKeys
  ];
  roleForm.auth_ids = auth_ids.join(',');
}

/* 获取所有菜单的ID */
const handleGetMenuIds = (menuData) => {
  for (let i = 0; i < menuData.length; i++) {
    state.allKeys.push(menuData[i].id);
    if (menuData[i].items.length > 0) {
      handleGetMenuIds(menuData[i].items);
    }
  }
}
/* 检查父级是否选中 */
const handleCheckedKeys = (id, data, newArr) => {
  data.forEach((item) => {
    if (item.id == id) {
      if (item.items.length == 0) {
        newArr.push(item.id);
      }
    } else {
      if (item.items.length != 0) {
        handleCheckedKeys(id, item.items, newArr);
      }
    }
  });
}
/* 点击分配菜单按钮 */
const handleAssignMenu = (row) => {
  console.log(row.auth_ids);
  if (row.auth_ids !== null) {
    let newArr = [];
    console.log(new Set(row.auth_ids.split(',')));
    let auth_ids = [...new Set(row.auth_ids.split(','))];
    console.log(auth_ids);
    auth_ids.forEach((item) => {
      handleCheckedKeys(item, state.menuData, newArr);
    });
    state.checkedKeys = newArr.map(Number);
    treeRef.value.setCheckedKeys(state.checkedKeys);

  }
  // clearData();
  setActiveName('two');
  methodType.value = 'PUT';
  roleForm.id = row.id;
  roleForm.name = row.name;
  roleForm.auth_ids = row.auth_ids;
}

/*关闭模态框以后的自定义操作 */
function handleCustomOperation () {
  roleForm.id = '';/* 这个还需要手动清除 */
  roleForm.selectAll = false;
  treeRef.value.setCheckedKeys([104])
}

/* 自定义校验，提交表单前操作 */
const handleValidAssignment = () => {
  let checkedNodes = treeRef.value.getCheckedNodes();
  if (methodType.value === 'PUT' && roleForm.id === '') {
    ElMessage.warning(`请点击右侧分配菜单进入`);
    return false;
  }
  if (checkedNodes.length === 0) {
    ElMessage.warning(`至少选择一个权限`);
    return false;
  }
  return true;
}

watch(() => roleForm.selectAll, (newV, oldV) => {
  console.log(newV);
  if (newV) {
    state.checkedKeys = state.allKeys;
    roleForm.auth_ids = state.checkedKeys.join(',');
  } else {
    state.checkedKeys = [104];
    roleForm.auth_ids = '104';
  }
  treeRef.value.setCheckedKeys(state.checkedKeys);
})
getTableInfo();
getMyRoleInfo();
</script>
<style lang="css" scoped>
/* 去除边框 */
.container {
  border-width: 0;
}

/* layout-布局 */
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  /* height: 100%; */
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.textAlignCenter {
  text-align: center;
}

/* 修改select的盒模型 */
.el-select {
  display: block;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 修改该属性值  查询条件，查询结果得样式 */
.el-breadcrumb {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
}

.width400 {
  width: 400px;
}

.width800 {
  max-width: 800px;
}

.wzg-center {
  margin: auto;
  padding: 50px 50px 15px;
  border: 1px solid #ebeef5;
  border-radius: 5px;
}

/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
